package web.interceptor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

import kit.token.TokenValidator;

/**
 * @ClassName: MessageInterceptor
 * @Description: jwt统一连接器
 * @author yyw
 * @date 2015年9月7日 上午1:55:22
 * 
 */
public class JwtInterceptor implements Interceptor {

	public void intercept(Invocation ai) {
		Controller controller=ai.getController();
		HttpServletRequest request = controller.getRequest();
		String appkey = request.getHeader("appkey");
		String authorization = request.getParameter("authorization");
		if(StringUtils.isBlank(authorization)){
			authorization = request.getHeader("authorization");// header再找
			if(StringUtils.isBlank(authorization)){
				authorization = getBody(request);// 从body获取信息
			}
		}
		if (StringUtils.isBlank(appkey)) {
			controller.renderJson("{\"status\":201,\"msg\":\"Request Doesn't has appkey header.\"}");
		} else {
			try {
				Map<String, String> data = TokenValidator.validate(appkey, authorization);
				request.setAttribute("data", data);
				ai.invoke();
			} catch (Exception e) {
				e.printStackTrace();
				controller.renderJson("{\"status\":202,\"msg\":\"validation error please checked  authorization\"}");
			}
		}

	}

	public static String getBody(HttpServletRequest request) {

		String body = null;
		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader bufferedReader = null;

		try {
			InputStream inputStream = request.getInputStream();
			if (inputStream != null) {
				bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
				char[] charBuffer = new char[128];
				int bytesRead = -1;
				while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
					stringBuilder.append(charBuffer, 0, bytesRead);
				}
			} else {
				stringBuilder.append("");
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}

		body = stringBuilder.toString();
		return body;
	}
}
